/**
 * 用户信息
 */

import httpApi from "../../service/api/basic.service";

const types = {
    USER_INFO: 'USER_INFO',
    USER_ID: 'USER_ID'
}

const store = { 
    namespaced: true,
    state: {
        userData: null,
        userId: null
    },

    getters: {
        userData: state => {
            if(!state.userData) {
                state.userData = sessionStorage.getItem('USERINFO_DATA') ? JSON.parse(sessionStorage.getItem('USERINFO_DATA')) : '';
            }

            return state.userData
        },
        userId: state => {

            return state.userId
        }
    },

    mutations: {
        [types.USER_INFO] (state, data) {  
            state.userData = data
        },
        [types.USER_ID] (state, data) {  
            state.userId = data
        }
    },

    actions: {
        // 获取用户信息
        getUserInfo ({ commit }, params) {
            return new Promise( (resolve, reject) => {
                httpApi.getUserByTgt(params).then(res => {
                    const result = res.data;
                    console.log(result.data)
                    if(result.code == 200) {
                        let data = result.data.userInfo;
                        if(result.data.userType === 'ZRR') {
                            data.userType = 'ZRR';
                            data = {...data, ...result.data.businessInfo};
                            if(Object.keys(data.accountInfo).length == 0) {
                                data.accountInfo = {
                                    gender: "",
                                    idcardNo: data.id_number,
                                    personName: data.nickName
                                }
                            }
                        }
                        if(result.data.userType === 'FR') {
                            data.userType = 'FR';
                            data.customer_id = data.customer_no;
                            data.mobile = data.tele_phone;
                            data.accountInfo = {
                                gender: "",
                                idcardNo: data.legal_id_number,
                                personName: data.legal_name
                            }
                        }
                        console.log(data)
                        sessionStorage.setItem('USERINFO_DATA', JSON.stringify(data));
                        commit(types.USER_INFO, data);
                        resolve(data);
                        
                    }else {
                        reject(result)
                    }
    
                }).catch (error => {
                    reject(error)
                })
            })
        }
    }
    
}


export default store;